<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>组件事件</title>
    <style>
        .product {
            width: 200px;
            height: 200px;
            background-color: rgb(231, 247, 201);
            border: 1px solid red;
            float: left;
        }
    </style>
</head>

<body>
    <div id="app" >
        <div >
            <my-product 
                v-for="product in goods" 
                :key="product.id" :pname="product.name" 
                :pid="product.id"
                :price="product.price"
                v-on:add-cart="addCart"     
            />
        </div>


    </div>
    <script src="./js/vue.js"></script>
    <script>
        //组件的定义
        /*---------------------------组件--------------------*/
        Vue.component('my-product', {
            //数据必须是一个函数，而且要返回一个数据对象
            data() {
                return {
                }
            },
            props: ['pid', 'pname', "price"],
            methods: {
                addCart() {
                    console.log('添加到购物车')

                }
            },
            //组件模板
            template: `
            <div class="product">
                <h2>{{pname}}</h2>
                <p>{{pid}}</p>
                <p>价格：{{price}}$</p>
                <button @click="$emit('add-cart',pid)">加入购物车</button>
            </div>`
        })
        /*---------------------------实例--------------------*/
        const app = new Vue({
            el: '#app',
            data: {
                goods: [
                    {
                        id: 1,
                        name: '兰博基尼',
                        "price": '1500'
                    },
                    {
                        id: 2,
                        name: '保时捷',
                        "price": '300'
                    },
                    {
                        id: 3,
                        name: '布加迪威龙',
                        "price": '2500'
                    },
                ],
                cart: [],
            },
            methods:{
                addCart(id){
                    this.cart.push(id)
                    console.log("this.cart.push(id)")
                }
            }

        })
    </script>

</body>

</html>